package com.bit.webhttp.V2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

//表示一个Http请求，并解析
public class HttpRequest {
    private String method;
    private String url;
    private String version;
    private Map<String,String> headers = new HashMap<>();
    private Map<String,String> parameters = new HashMap<>();

    //请求的构造逻辑，用工厂模式来构造
    //此处的参数，就是从socket中获取的InputStream对象
    public static HttpRequest build(InputStream inputStream) throws IOException {
        HttpRequest request = new HttpRequest();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        //此处的build的过程就是解析请求的过程
        //1.解析首行
        String firstLine = bufferedReader.readLine();
        String[] FirstLineTokens = firstLine.split(" ");
        request.method = FirstLineTokens[0];
        request.url = FirstLineTokens[1];
        request.version = FirstLineTokens[2];
        //2.解析url中的参数
        int pos = request.url.indexOf("?");
        if(pos != -1){
            //pos返回 ？的下标
            String parameters = request.url.substring(pos+1);
            //切分ur“？”后面的内容
            parseKV(parameters,request.parameters);
        }
        //3.解析header
        String line = "";
        while((line = bufferedReader.readLine()) != null && line.length()!=0){
            String[] headerTokens = line.split(": ");
            request.headers.put(headerTokens[0],headerTokens[1]);
        }
        //4.解析body（暂不考虑）
        return request;
    }

    private static void parseKV(String input, Map<String, String> output) {
        String[] kvTokens = input.split("&");
        for(String kv:kvTokens){
            String[] result = kv.split("=");
            output.put(result[0],result[1]);
        }
    }
    //添加一些getter方法，不要setter

    public String getMethod() {
        return method;
    }

    public String getUrl() {
        return url;
    }

    public String getVersion() {
        return version;
    }
    //此处的getter手写方便些
    public String getHeader(String key){
        return headers.get(key);
    }
    public  String getParameter(String key){
        return parameters.get(key);
    }

    @Override
    public String toString() {
        return "HttpResponse{" +
                "method='" + method + '\'' +
                ", url='" + url + '\'' +
                ", version='" + version + '\'' +
                ", headers=" + headers +
                ", parameters=" + parameters +
                '}';
    }
}

